package org.elanfox.intellicommunity.msg.server.base;

import io.netty.buffer.Unpooled;
import org.apache.poi.util.HexRead;
import org.elanfox.intellicommunity.msg.constant.MsgConstant;
import org.elanfox.intellicommunity.msg.ienum.CmdEnums;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/3/16
 */
public class MsgCommunicationUtils {
    public static String buildRequest(String deviceAddr, CmdEnums.Code cmdCode, String hexData, String hexLength) {
        StringBuilder requestData = new StringBuilder(MsgConstant.FRONT_CODE);

        //校验码
        String rawCrc16 = MsgConstant.P2P_CODE + hexLength;
        String crc16 = CRC16Util.crc16Calc(rawCrc16, 4);
        requestData.append(crc16).append(MsgConstant.P2P_CODE).append(hexLength);

        //消息体
        //校验码:待crc的：帧选项+命令代码+设备地址+数据（也就是校验码后面所有）
        String rawDataCrc = MsgConstant.P2P_FRAME + cmdCode.getCode() + deviceAddr + hexData;
        String dataCrc = CRC16Util.crc16Calc(rawDataCrc, 4);
        requestData.append(dataCrc).append(MsgConstant.P2P_FRAME).append(cmdCode.getCode()).append(deviceAddr).append(hexData);

        return requestData.toString();
    }

    public static WriteResult request(String hexAddr, CmdEnums.Code cmdCode, String hexData, String hexLength) {
        String requestData = buildRequest(hexAddr, cmdCode, hexData, hexLength);

        if (MsgChannelRegister.isExist(hexAddr)) {
            //发送指令
            MsgChannelRegister.get(hexAddr).writeAndFlush(Unpooled.copiedBuffer(HexRead.readFromString(requestData)));
            return new WriteResult(true);
        } else {
            return new WriteResult(false, "设备" + hexAddr + "未连接");
        }
    }
}
